﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid;

using WCFMINERP.Contracts.DataContracts;
using WCFMINERP.Order.IView;
using WCFMINERP.Order.Presenter;
using WCFMINERP.MODEL.Order;
using WCFMINERP.MODEL;
using WCFMINERP.ComControls;
using WCFMINERP.COM;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors;
using System.Runtime.InteropServices;

namespace WCFMINERP.Order.Forms
{

    public delegate void ShowOrderInfoHander(int orderInfoId);
    public delegate void DeleteOrderInfoHander(int orderInfoId);
    public delegate void LinkTemplate();
    public partial class FrmOrder : FrmParent, IOrderView
    {

        [DllImport("shell32.dll ")]
        public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
        OrderPresenter _presenter;

        public ShowOrderInfoHander showOrderInfoHander;
        public DeleteOrderInfoHander deleteOrderInfoHander;

        public LinkTemplate linkTemplate;

        public FrmOrder()
        {
            InitializeComponent();

        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //控件设置

            splitContainer1.Panel1Collapsed = true;
            splitContainer1.Panel2Collapsed = false;

            splitContainer2.Panel1Collapsed = false;
            splitContainer2.Panel2Collapsed = true;


            OrderInfoList = new List<WCFMINERP.MODEL.OrderInfo>();
            ProducList = new List<WCFMINERP.MODEL.Order.ProductInfo>();
            PaperFaceList = new List<WCFMINERP.MODEL.Order.PaperFaceInfo>();
            PaperTypeList = new List<WCFMINERP.MODEL.Order.PaperTypeInfo>();
            CommonChargeItemList = new List<WCFMINERP.MODEL.Order.CommonChargeItemInfo>();


            //
            _presenter = new OrderPresenter(this);

            showOrderInfoHander = new ShowOrderInfoHander(ShowOrderInfo);
            deleteOrderInfoHander = new DeleteOrderInfoHander(DeleteOrderInfo);
            linkTemplate = new LinkTemplate(LinkProductTemplateNames);
            //绑定常用产品分类
            LinkDailyProducts(flpProduct);

            dtFechTime.DateTime = DateTime.Now.AddDays(-2);

            //绑定产品模板
            LinkProductTemplateNames();

        }

        private void LinkProductTemplateNames()
        {
            tscmbTemplate.Items.Clear();
            foreach (var item in _presenter.GetProductTemplateNames())
            {
                tscmbTemplate.Items.Add(item);
            }
        }

        #region 实现Iview接口

        /// <summary>
        /// 纸型combox
        /// </summary>
        public RepositoryItemComboBox cmboxPaperType
        {
            get
            {
                return comboboxPaperType;
            }

        }
        /// <summary>
        /// 纸面combox
        /// </summary>
        public RepositoryItemComboBox cmboxPaperFace
        {
            get { return comboboxPaperFace; }
        }
        /// <summary>
        /// 产品纸面combox
        /// </summary>
        public RepositoryItemComboBox cmboxOrderInfoPaperFace 
        {
            get 
            {
                return comboxOrderInfoPaperFace; 
            }
        }
        /// <summary>
        /// 产品纸型combox
        /// </summary>
        public  RepositoryItemComboBox cmboxOrderInfoPaperType 
        {
            get 
            {
                return comboxOrderInfoPaperType; 
            }
        }
        /// <summary>
        /// 公共计价项目combox
        /// </summary>
        public RepositoryItemCheckedComboBoxEdit cmboxCommonChargeItem
        {
            get { return CheckcmboxCommonChargeItem; }
        }
        /// <summary>
        /// 产品列表gc
        /// </summary>
        public GridControl GcOrderInfo { get { return gcOrderInfo; } }
        /// <summary>
        /// 照片列表gc
        /// </summary>
        public GridControl GcPhotoInfo { get { return gcPhotoInfo; } }
        /// <summary>
        /// 装载产品的控件容器
        /// </summary>
        public FlowLayoutPanel FlpProduct { get { return flpProduct; } }
        /// <summary>
        ///  装载订单的控件容器
        /// </summary>
        public FlowLayoutPanel FlpShowOrderInfo { get { return flpShowOrderInfo; } }

        /// <summary>
        /// 公共收费项目列表
        /// </summary>
        public List<WCFMINERP.MODEL.Order.CommonChargeItemInfo> CommonChargeItemList { get; set; }
        /// <summary>
        /// 纸面列表
        /// </summary>
        public List<WCFMINERP.MODEL.Order.PaperFaceInfo> PaperFaceList { get; set; }
        /// <summary>
        /// 纸面列表
        /// </summary>
        public List<WCFMINERP.MODEL.Order.PaperTypeInfo> PaperTypeList { get; set; }

        /// <summary>
        /// 待开单产品集合
        /// </summary>
        public List<WCFMINERP.MODEL.OrderInfo> OrderInfoList { get; set; }
        /// <summary>
        /// 产品列表
        /// </summary>
        public List<WCFMINERP.MODEL.Order.ProductInfo> ProducList { get; set; }
        /// <summary>
        /// 被选中添加照片的产品
        /// </summary>
        public WCFMINERP.MODEL.OrderInfo OrderInfoSelectedToAddPhotos { get; set; }


        /// <summary>
        /// 绑定产品分类
        /// </summary>
        /// <param name="productCategoryList"></param>
        /// <param name="flp"></param>
        public void LinkProductCategory(FlowLayoutPanel flpProductGategory)
        {
            _presenter.LinkProductCategory(flpProductGategory);
        }

        /// <summary>
        /// 绑定公共计价项目
        /// </summary>
        public void LinkCommonChargeItem()
        {
            _presenter.LinkCommonChargeItem();
        }

        /// <summary>
        /// 绑定常用产品
        /// </summary>
        /// <param name="productInfoList"></param>
        /// <param name="flp"></param>
        public void LinkDailyProducts(FlowLayoutPanel flp)
        {
            _presenter.LinkDailyProducts(flp);
        }

        /// <summary>
        /// 显示警告消息
        /// </summary>
        /// <param name="msg"></param>
        public void ShowImportMessage(string msg)
        {
            MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        # endregion

        //点击开单按钮
        private void tsbtnOrder_Click(object sender, EventArgs e)
        {


            try
            {
                if (MessageBox.Show("确认开单", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    OrderBag orderbag = new OrderBag();
                    orderbag.ShopId = Shop.ShopId;
                    orderbag.FetchTime = dtFechTime.DateTime;
                    orderbag.Remark = textBoxbagRemark.Text;
                    int rtnVal = _presenter.OrderAndProductXml(orderbag);
                    if (rtnVal == -1)
                    {
                        MessageBox.Show("未选择产品，请将照片文件夹拖拽到产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    gcPhotoInfo.DataSource = null;
                    gcPhotoInfo.RefreshDataSource();//将照片列表清空掉
                    //flpProduct.Controls.;
                    flpShowOrderInfo.Controls.Clear();//清空已经开过单的产品
                    MessageBox.Show("开单成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    if (splitContainer2.Panel2Collapsed == false)
                    {
                        splitContainer1.Panel1Collapsed = true;
                        splitContainer1.Panel2Collapsed = false;

                        splitContainer2.Panel2Collapsed = true;
                        splitContainer2.Panel1Collapsed = false;
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void gvOrderInfo_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            WCFMINERP.MODEL.OrderInfo oi = (WCFMINERP.MODEL.OrderInfo)gvOrderInfo.GetRow(e.RowHandle);
            if (oi != null)
            {
                gcPhotoInfo.DataSource = oi.PhotoList;
                gcPhotoInfo.RefreshDataSource();
            }
        }

        //显示所有产品分类
        private void tsbtnAllProduct_Click(object sender, EventArgs e)
        {
            #region 控件设置
            splitContainer1.Panel1Collapsed = false;
            splitContainer1.Panel2Collapsed = true;

            splitContainer2.Panel1Collapsed = false;
            splitContainer2.Panel2Collapsed = true;
            #endregion

            try
            {
                LinkProductCategory(flpProductGategory);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //显示常用产品列表
        private void tsbtnDailyProduct_Click(object sender, EventArgs e)
        {
            #region 控件设置
            splitContainer1.Panel1Collapsed = true;
            splitContainer1.Panel2Collapsed = false;

            splitContainer2.Panel1Collapsed = false;
            splitContainer2.Panel2Collapsed = true;
            #endregion
            try
            {
                LinkDailyProducts(flpProduct);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //去开单
        private void btnSelectPhoto_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel1Collapsed = true;
            splitContainer1.Panel2Collapsed = false;

            splitContainer2.Panel2Collapsed = true;
            splitContainer2.Panel1Collapsed = false;

            try
            {
                LinkGcPhoto();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        /// <summary>
        /// 绑定照片列表
        /// </summary>
        private void LinkGcPhoto()
        {
            try
            {
                WCFMINERP.MODEL.OrderInfo oi = gvOrderInfo.GetFocusedRow() as WCFMINERP.MODEL.OrderInfo;
                if (oi != null)
                {
                    gcPhotoInfo.DataSource = oi.PhotoList;
                    gcPhotoInfo.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        // 去开单
        private void btnGOOrder2_Click(object sender, EventArgs e)
        {
            GoToOrder();
        }

        // 去开单
        private void btnGOOrder1_Click(object sender, EventArgs e)
        {
            GoToOrder();
        }

        /// <summary>
        /// 初始化开单的产品界面
        /// </summary>
        private void GoToOrder()
        {
            try
            {
                gcOrderInfo.DataSource = _presenter._orderInfoList;
                gcOrderInfo.RefreshDataSource();

                splitContainer2.Panel1Collapsed = true;
                splitContainer2.Panel2Collapsed = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        /// <summary>
        ///  gcOrderInfo 单元格值改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvOrderInfo_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {

                WCFMINERP.MODEL.OrderInfo oi = gvOrderInfo.GetRow(e.RowHandle) as WCFMINERP.MODEL.OrderInfo;
                //取得附加收费项目集合
                if (e.Column.FieldName == "CommonChargeItemName")
                {
                    StringBuilder commonChargeItemIdList = new StringBuilder();
                    string[] commonChargeItemNameList;
                    if(e.Value.ToString()!=string.Empty)
                    {
                        commonChargeItemNameList = e.Value.ToString().Split(',');
                        for (int i = 0; i < commonChargeItemNameList.Length; i++)
                        {
                            WCFMINERP.MODEL.Order.CommonChargeItemInfo comitemInfo = CommonChargeItemList.First(c => c.CommonChargeItemName == commonChargeItemNameList[i].Trim());
                            commonChargeItemIdList.Append(comitemInfo.CommonChargeItemId.ToString());
                            if (commonChargeItemNameList.Length - i != 1)
                            {
                                commonChargeItemIdList.Append("|");
                            }
                        }
                        oi.CommonChargeItemIdList = commonChargeItemIdList.ToString();
                    }
                }
                //根据选择的纸型名称改变其纸型ID
                if (e.Column.FieldName == "PaperFaceName")
                {
                    foreach (var item in oi.PhotoList)
                    {
                        item.PaperFaceId =PaperFaceList.First(p => p.PaperFaceName == e.Value.ToString()).PaperFaceId;
                        item.PaperFaceName = e.Value.ToString();
                    }
                }
                //根据选择的纸面名称改变其纸面ID
                if (e.Column.FieldName == "PaperTypeName")
                {
                    foreach (var item in oi.PhotoList)
                    {
                        item.PaperTypeID =PaperTypeList.First(p => p.paperTypeName == e.Value.ToString()).paperTypeId;
                        item.PaperTypeName = e.Value.ToString();
                    }
                }

                gcPhotoInfo.RefreshDataSource();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
        /// <summary>
        /// gcPhoto 单元格值改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvPhotoInfo_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                WCFMINERP.MODEL.PhotoInfo phtoInfo = gvPhotoInfo.GetRow(e.RowHandle) as WCFMINERP.MODEL.PhotoInfo;
                //根据选择的纸型名称改变其纸型ID
                if (e.Column.FieldName == "PaperTypeName")
                {
                    phtoInfo.PaperTypeID = PaperTypeList.First(p => p.paperTypeName == e.Value.ToString()).paperTypeId;
                }
                //根据选择的纸面名称改变其纸面ID
                if (e.Column.FieldName == "PaperFaceName")
                {
                    phtoInfo.PaperFaceId = PaperFaceList.First(p => p.PaperFaceName == e.Value.ToString()).PaperFaceId;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnSetting_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 显示产品信息
        /// </summary>
        /// <param name="orderInfoId"></param>
        private void ShowOrderInfo(int orderInfoId)
        {
            try
            {
                List<WCFMINERP.MODEL.OrderInfo> oiList = _presenter._orderInfoList.Where(o => o.OrderProductId == orderInfoId).ToList();
                FrmOrderInfo frm = new FrmOrderInfo(oiList);
                frm._presenter = _presenter;
                frm.showtype = ShowType.addPhoto;
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 删除产品
        /// </summary>
        /// <param name="orderInfoId"></param>
        private void DeleteOrderInfo(int orderInfoId)
        {
            WCFMINERP.MODEL.OrderInfo oi = _presenter._orderInfoList.FirstOrDefault(o => o.OrderProductId == orderInfoId);
            _presenter._orderInfoList.Remove(oi);
            _presenter.DeleteOrderInfoControl(oi.OrderProductId);
            _presenter.RefreshControlStatus(oi.ControlName);
        }

        private void gvOrderInfo_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle > -1)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
            }
        }

        private void gvPhotoInfo_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle > -1)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
            }
        }

        private void FrmOrder_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {

                e.Cancel = true;
                this.Hide();
            }
        }

        /// <summary>
        /// 绑定模板产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tscmbTemplate_DropDownClosed(object sender, EventArgs e)
        {
            #region 控件设置
            splitContainer1.Panel1Collapsed = true;
            splitContainer1.Panel2Collapsed = false;

            splitContainer2.Panel1Collapsed = false;
            splitContainer2.Panel2Collapsed = true;
            #endregion
            if (tscmbTemplate.Items.Count > 0)
            {
                try
                {
                    _presenter.LinkTemplateProducts(flpProduct, tscmbTemplate.SelectedItem.ToString());
                }
                catch { }

            }
        }

        /// <summary>
        /// 参数设置菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmenuPramConfig_Click(object sender, EventArgs e)
        {
            FrmSetting frm = new FrmSetting();
            frm.ShowDialog();
        }

        /// <summary>
        /// 产品模板菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMenuProductTemplate_Click(object sender, EventArgs e)
        {
            FrmProductTemplate frm = new FrmProductTemplate(_presenter);
            frm.ShowDialog(this);
        }
        /// <summary>
        /// 开单完成后把开过单的产品刷新到初始状态
        /// </summary>
        /// <param name="inList"></param>
        public void ClearProductStatus()
        {
            //foreach (WCFMINERP.MODEL.OrderInfo order in inList)
            //{
            //    string productName = order.OrderProductName.Substring(order.OrderProductName.LastIndexOf("_"));
            //    flpProduct.Controls.
            //}
            foreach (Control control in flpProduct.Controls)
            {
                Button btn = (Button)control;
                btn.BackColor = Color.Transparent;
            }
        }

        //打开文件夹
        private void OpenPath(string path)
        {
   
            ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                     new StringBuilder(path), new StringBuilder(string.Empty), 1);
        }

        private void gvPhotoInfo_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "OrilPicPath")
            {
                if (!string.IsNullOrEmpty(e.CellValue.ToString()))
                {
                    OpenPath(e.CellValue.ToString());
                }
            }
        }

        private void tsbtnQuery_Click(object sender, EventArgs e)
        {
            #region 控件设置
            splitContainer1.Panel1Collapsed = true;
            splitContainer1.Panel2Collapsed = false;

            splitContainer2.Panel1Collapsed = false;
            splitContainer2.Panel2Collapsed = true;
            #endregion
            _presenter.LinkQueryProuducts(flpProduct, tstxtProductNameOrMN.Text.Trim().ToUpper());
        }

        private void tstxtProductNameOrMN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == (int)Keys.Enter)
            {
                tsbtnQuery_Click(null, null);
            }
        }

    }
}
